﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WareHouse.App
{
    using System.Drawing.Printing;

    using DevExpress.XtraGrid;
    using DevExpress.XtraPrinting;

    using WareHouse.Contract.Models;
    using WareHouse.Contract.Services;
    using WareHouse.Service.Services;

    public partial class FrmManageImportHistory : Form
    {
        private IWareHouseService wareHouseService;

        private List<ImportDetailModel> listImportDetailModels; 
        public FrmManageImportHistory()
        {
            wareHouseService=new WareHouseService();
            InitializeComponent();
        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }
        private void RefreshLabel()
        {
            
            lblDate.Text = "";
            lblEmployerName.Text = "";
            lblImportId.Text = "";
            lblWareHouseName.Text = "";
            
        }

        private ImportModel modelImport;
        private void gridView1_Click(object sender, EventArgs e)
        {
            try
            {
                modelImport = (ImportModel)gridView1.GetRow(gridView1.GetSelectedRows()[0]);
                if (modelImport != null)
                {
                    
                    lblDate.Text = modelImport.DateCreate.ToString("dd/MM/yyyy");
                    lblEmployerName.Text = modelImport.EmployerName;
                    lblImportId.Text = modelImport.ImportId;
                    lblWareHouseName.Text = modelImport.WareHouseName;
                    

                    LoadDataItemByImportId(modelImport.ImportId);

                }
            }
            catch (Exception)
            {


            }

        }

        private void LoadDataItemByImportId(string ImportId)
        {
            gridItems.DataSource = wareHouseService.ListItemByImportId(ImportId).ToArray();
            ReCanculateSTT();
        }

        private void ReCanculateSTT()
        {
            for (int i = 0; i < gridView2.RowCount; i++)
            {
                gridView2.SetRowCellValue(i, "Stt", i + 1);
            }

        }

        private ImportDetailModel modelDetail;
        private void gridView2_Click(object sender, EventArgs e)
        {
            try
            {
                modelDetail = (ImportDetailModel)gridView2.GetRow(gridView2.GetSelectedRows()[0]);
                if (modelDetail != null)
                {
                    txtQantityOgrinal.Text = modelDetail.Quantity.ToString();
                }
            }
            catch (Exception)
            {


            }

        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (txtQantityOgrinal.Text == "" || int.Parse(txtQantityOgrinal.Text) <= 0)
            {
                MessageBox.Show("Chọn sản phẩm cần chỉnh sữa");
                return;
            }

            if (btnEdit.Text == "Chỉnh sữa hóa đơn")
            {
                txtQuantityChange.Enabled = true;
                gridItems.Enabled = false;
                gridListHd.Enabled = false;
                btnEdit.Text = "Lưu";
                return;
            }
            if (btnEdit.Text == "Lưu")
            {
                if (txtQuantityChange.Text == "" || int.Parse(txtQuantityChange.Text) <= 0)
                {
                    MessageBox.Show("Số lượng muốn thay đổi phải lớn hơn 0");
                    return;
                }



                var editModel = new EditExpAndImpModel();
                editModel.ItemId = modelDetail.ItemId;
                editModel.QuantityChangeTo = int.Parse(txtQuantityChange.Text);
                editModel.QuantityOrginal = modelDetail.Quantity;
                editModel.WareHouseId = modelImport.WareHouseId;

                if (wareHouseService.CheckQuantityInWareHouse(editModel))
                {
                    if (wareHouseService.UpdateQuantityInImported(editModel))
                    {
                        txtQuantityChange.Enabled = false;
                        gridItems.Enabled = true;
                        gridListHd.Enabled = true;
                        btnEdit.Text = "Chỉnh sữa hóa đơn";
                        MessageBox.Show("Đã sữa hóa đơn thành công");
                        LoadDataItemByImportId(modelImport.ImportId);
                        return;
                    }
                    MessageBox.Show("Lỗi thiết bị không thể sữa hóa đơn này");
                    return;
                }
                MessageBox.Show("Số lượng hàng trong kho không đủ");


            }


        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            txtQuantityChange.Enabled = false;
            gridItems.Enabled = true;
            gridListHd.Enabled = true;
            btnEdit.Text = "Chỉnh sữa hóa đơn";
        }

        private void FrmManageImportHistory_Load(object sender, EventArgs e)
        {
            CheckRole();
            this.RefreshLabel();
            gridListHd.DataSource = wareHouseService.ListAllImport().ToArray();
        }
        private void CheckRole()
        {
            if (!wareHouseService.R(General.groupUserId, "importhistory_editquantity"))
            {
                btnEdit.Enabled = false;

            }
            if (!wareHouseService.R(General.groupUserId, "importhistory_printagain"))
            {
                button1.Enabled = false;

            }


        }

        private void printLink_CreateReportHeaderArea(object sender, DevExpress.XtraPrinting.CreateAreaEventArgs e)
        {
            // draw title
            DevExpress.XtraPrinting.TextBrick brickTitle;

            brickTitle = e.Graph.DrawString("PHIẾU NHẬP KHO", Color.Black, new RectangleF(0, 0, 725, 40), DevExpress.XtraPrinting.BorderSide.None);

            brickTitle.Font = new Font("Tahoma", 22);

            brickTitle.StringFormat = new DevExpress.XtraPrinting.BrickStringFormat(StringAlignment.Center);




            // draw column left


            DevExpress.XtraPrinting.TextBrick brickleft1;

            brickleft1 = e.Graph.DrawString(
                  "Số HD:     "
                + lblImportId.Text
                + Environment.NewLine + Environment.NewLine
                + "Kho nhập:  " + lblWareHouseName.Text
                + Environment.NewLine + Environment.NewLine, Color.Black, new RectangleF(0, 50, 200, 60), DevExpress.XtraPrinting.BorderSide.None);

            brickleft1.Font = new Font("Tahoma", 10);

            brickleft1.StringFormat = new BrickStringFormat(StringAlignment.Near);


            // draw column mid


            DevExpress.XtraPrinting.TextBrick brickleft2;


            brickleft2 = e.Graph.DrawString(
                  "NV lập HD:     "
                + lblEmployerName.Text
                + Environment.NewLine + Environment.NewLine
                + "Ngày lập HD:  " + lblDate.Text
                + Environment.NewLine + Environment.NewLine, Color.Black, new RectangleF(460, 50, 280, 60), DevExpress.XtraPrinting.BorderSide.None);

            brickleft2.Font = new Font("Tahoma", 10);

            brickleft2.StringFormat = new BrickStringFormat(StringAlignment.Near);

            // draw column right


          

            // draw title detail
            DevExpress.XtraPrinting.TextBrick brickTitleDetail;

            brickTitleDetail = e.Graph.DrawString("Chi Tiết Phiếu nhập", Color.Black, new RectangleF(0, 115, 725, 20), DevExpress.XtraPrinting.BorderSide.None);

            brickTitleDetail.Font = new Font("Tahoma", 12, FontStyle.Bold);

            brickTitleDetail.StringFormat = new DevExpress.XtraPrinting.BrickStringFormat(StringAlignment.Center);




        }
        private void PrintListItemInGrid(GridControl gridControl)
        {
            PrintableComponentLink printLink = new PrintableComponentLink();
            printLink.CreateReportHeaderArea += this.printLink_CreateReportHeaderArea;

            PrintingSystem printingSystem = new PrintingSystem();
            printingSystem.Links.AddRange(new object[] { printLink });

            printLink.PaperKind = PaperKind.A4;
            printLink.Component = gridControl;

            printLink.Images.Add(Properties.Resources.Logo);

            printLink.Margins.Top = 200;
            printLink.Margins.Left = 25;
            printLink.Margins.Right = 25;


            var agencyName = "";
            var agencyAddress = "";
            var agencyPhone = "";



            var currentAgency = wareHouseService.GetCurrentAgency();
            if (currentAgency == null)
            {
                MessageBox.Show("Hiện tại chưa có đại lý nào được chọn");
                return;
            }

            agencyAddress = currentAgency.AgencyAddress;
            agencyName = currentAgency.AgencyName;
            agencyPhone = currentAgency.Phone;
            #region Define content of header
            PageHeaderArea pgHArea = new PageHeaderArea();

            pgHArea.Font = new Font(new FontFamily("Tahoma"), 12, FontStyle.Regular);

            pgHArea.Content.AddRange(
                new string[]
                    {
                        "Đại lý : "+ agencyName+ Environment.NewLine 
                        + "Địa chỉ : "+agencyAddress + Environment.NewLine
                        + "Điện thoại : "+agencyPhone + Environment.NewLine + "  " + Environment.NewLine
                        + Environment.NewLine + "" + Environment.NewLine + ""
                        + Environment.NewLine, Environment.NewLine + Environment.NewLine + "", "[Image 0]"
                    });

            #endregion
            #region Define content of footer
            PageFooterArea pgFArea = new PageFooterArea();

            pgFArea.Font = new Font(new FontFamily("Tahoma"), 10, FontStyle.Bold);

            decimal totalSummary = 0;
            var summaryValue = this.gridView2.Columns["Total"].SummaryItem.SummaryValue;
            if (summaryValue != null && decimal.TryParse(summaryValue.ToString(), out totalSummary))
            {
                pgFArea.Content.AddRange(
                new string[]
                    {"","",
                        "Thành tiền : "+ String.Format("{0:N0}",totalSummary)+" VND"+Environment.NewLine
                    +"Bằng chữ :"+ General.DetachMoney((double)totalSummary)
                      
                  
                    });

            }

            #endregion

            // Create a PageHeaderFooter object for this link.
            printingSystem.Links[0].PageHeaderFooter = new PageHeaderFooter(pgHArea, pgFArea);


            printLink.ShowPreview();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                this.PrintListItemInGrid(gridItems);
            }
            catch (Exception)
            {
                
                
            }
        }

    }
}
